package com.htdst.mockserver.tcpserver;

import java.io.IOException;
import java.net.ServerSocket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import org.apache.log4j.Logger;

import com.htdst.mockserver.util.Config;

public class SocketServer
{
	private static final Logger	logger		= Logger.getLogger(SocketServer.class);
	private ServerSocket		server		= null;
	private ExecutorService		threadPool	= null;
	private boolean				started		= false;

	public SocketServer() throws IOException
	{
		server = new ServerSocket(Config.getPort());
		threadPool = Executors.newFixedThreadPool(Config.getThreadPoolSize());
	}

	public boolean isStarted()
	{
		return started;
	}

	public void start()
	{
		if (!server.isBound())
		{
			logger.error("Fail to bound server on:" + server.getLocalPort());
			return;
		}
		logger.debug("Starting server on :" + server.getLocalPort());

		while (!server.isClosed())
		{
			try
			{
				threadPool.execute(new MainframeSocketHandler(server.accept()));
				if (!started)
				{
					started = true;
				}
			}
			catch (IOException e)
			{
				logger.error("Error occurs when accept the connection", e);
			}
		}
	}

	public void shutdown()
	{
		try
		{
			server.close();
		}
		catch (IOException e)
		{
			logger.error("Error occurs when close server.", e);
		}
	}

}